package com.atguigu.eduservice.controller;


import com.atguigu.annotation.WebLog;
import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 陈烨庆
 * @since 2022-01-24
 */
@RestController
@RequestMapping("/eduservice/edu-video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private VodClient vodClient;

    @WebLog("添加小节")
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    @WebLog("查询小节")
    @GetMapping("getVideoInfo/{id}")
    public R getVideoInfo(@PathVariable String id) {
        EduVideo eduVideo = eduVideoService.getById(id);
        return R.ok().data("video", eduVideo);
    }

    @WebLog("更新小节")
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

    /**
     * TODO 后面需要完善，删除小节的时候 同时删除里面的视频
     * @param id
     * @return
     */
    @WebLog("删除小节")
    @DeleteMapping("removeVideo/{id}")
    public R removeVideo(@PathVariable String id) {
        EduVideo eduVideo = eduVideoService.getById(id);

        // 视频id不为空则删除视频
        if (!StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
            R result = vodClient.deleteAliyunVideo(eduVideo.getVideoSourceId());
            if (result.getCode() == 20001) {
                throw new GuliException(20001, "删除视频失败，熔断器...");
            }
        }
        // 删除小节
        eduVideoService.removeById(id);
        return R.ok();
    }
}

